package com.example.mybatisdemo1.controller;

import com.example.mybatisdemo1.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    

    @Autowired
    private TransactionDefinition transactionDefinition;

    @Transactional
    @RequestMapping("/transfer")
    public int transferAccounts(){
        // 开启事务
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        int ret1 = accountService.outAccount("用户A");
        int ret2 = accountService.inAccount("用户B");


        // dataSourceTransactionManager.rollback(transactionStatus);
        return (ret1 + ret2);
    }

}
